<template>
  <ResizePageWrapper>
    <template #resizeLeft>
      <BasicTree
        :title="t('目录信息')"
        ref="asyncTreeRef"
        search
        toolbar
        :clickRowToExpand="true"
        expandOnSearch
        :treeData="treeData"
        :load-data="onLoadData"
        :fieldNames="{ key: 'id', title: 'name' }"
        @select="handleSelect"
      />
    </template>

    <template #resizeRight>
      <BasicTable @register="registerTable">
        <template #toolbar>
          <a-button type="primary" @click="handleCreate" v-auth="'areaManager:add'">{{
            t('新增区域')
          }}</a-button>
        </template>
        <template #action="{ record }">
          <TableAction
            :actions="[
              {
                label: '编辑',
                auth: 'areaManager:edit',
                onClick: handleEdit.bind(null, record),
              },
              {
                label: '删除',
                auth: 'areaManager:delete',
                color: 'error',
                popConfirm: {
                  title: t('是否确认删除'),
                  confirm: handleDelete.bind(null, record),
                },
              },
            ]"
          />
        </template>
      </BasicTable>
    </template>
    <AreaModal @register="registerModal" @success="handleSuccess" />
  </ResizePageWrapper>
</template>
<script lang="ts" setup>
  import { ref, unref, onMounted, reactive, toRefs } from 'vue';
  import { BasicTable, useTable, TableAction, FormSchema, BasicColumn } from '/@/components/Table';
  import { BasicTree, TreeActionType, TreeItem } from '/@/components/Tree';
  import { getAreaProvinceList, getAreaList, deleteArea } from '/@/api/system/area';
  import { ResizePageWrapper } from '/@/components/Page';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useModal } from '/@/components/Modal';
  import { uniq } from 'lodash-es';
  import AreaModal from './components/AreaModal.vue';
  import { usePermission } from '/@/hooks/web/usePermission';
  const { t } = useI18n();
  const searchFormSchema: FormSchema[] = [
    {
      field: 'keyword',
      label: '',
      component: 'Input',
      componentProps: {
        placeholder: t('请输入区域名称'),
      },
    },
  ];

  const columns: BasicColumn[] = [
    {
      title: t('编号'),
      dataIndex: 'code',
      width: 120,
      // sorter: true,
      align: 'center',
      resizable: true,
    },
    {
      title: t('名称'),
      dataIndex: 'name',
      width: 120,
      // sorter: true,
      align: 'center',
      resizable: true,
    },
    {
      title: t('简拼'),
      dataIndex: 'simpleSpelling',
      width: 120,
      // sorter: true,
      align: 'center',
      resizable: true,
    },
    {
      title: t('快速查询'),
      dataIndex: 'quickQuery',
      width: 120,
      // sorter: true,
      align: 'center',
      resizable: true,
    },
    {
      title: t('级别'),
      dataIndex: 'layer',
      width: 120,
      // sorter: true,
      align: 'center',
      resizable: true,
      customRender: ({ text }) => {
        switch (text) {
          case 1:
            return t('省');
          case 2:
            return t('市');
          case 3:
            return t('区');
          case 4:
            return t('街道');
        }
      },
    },
    {
      title: t('备注'),
      // sorter: true,
      dataIndex: 'remark',
      align: 'center',
      resizable: true,
    },
  ];

  const { notification } = useMessage();

  const selectAreaId = ref('');

  const { filterColumnAuth, hasPermission } = usePermission();

  const filterColumns = filterColumnAuth(columns, true);

  const [registerModal, { openModal }] = useModal();
  const [registerTable, { reload }] = useTable({
    title: t('行政区域列表'),
    api: getAreaList,
    rowKey: 'id',
    columns: filterColumns,
    formConfig: {
      rowProps: {
        gutter: 16,
      },
      schemas: searchFormSchema,
      showResetButton: false,
    },
    beforeFetch: (params) => {
      //发送请求默认新增  左边树结构所选区域id
      return { ...params, id: selectAreaId.value };
    },
    useSearchForm: true,
    showTableSetting: true,
    striped: false,
    actionColumn: {
      width: 88,
      title: t('操作'),
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
    tableSetting: {
      size: false,
    },
    customRow: (record) => {
      return {
        ondblclick: () => {
          if (hasPermission('areaManager:edit')) {
            handleEdit(record);
          }
        },
      };
    },
  });
  const treeData = ref<TreeItem[]>([]);
  const asyncTreeRef = ref<Nullable<TreeActionType>>(null);

  function onLoadData(treeNode) {
    return new Promise((resolve: (value?: unknown) => void) => {
      getAreaList({ id: treeNode.id }).then((res) => {
        const asyncTreeAction: TreeActionType | null = unref(asyncTreeRef);
        if (asyncTreeAction) {
          asyncTreeAction.updateNodeByKey(treeNode.key, { children: res });
          asyncTreeAction.setExpandedKeys(
            uniq([treeNode.key, ...asyncTreeAction.getExpandedKeys()]),
          );
        }
        resolve();
        return;
      });
    });
  }

  async function fetch() {
    treeData.value = (await getAreaProvinceList()) as unknown as TreeItem[];
  }

  onMounted(() => {
    fetch();
  });
  function handleCreate() {
    openModal(true, {
      isUpdate: false,
      ...areaInfo,
    });
  }

  function handleEdit(record: Recordable) {
    openModal(true, {
      id: record.id,
      isUpdate: true,
    });
  }

  function handleDelete(record: Recordable) {
    deleteArea([record.id]).then((_) => {
      reload({ searchInfo: { id: selectAreaId.value } });
      notification.success({
        message: t('提示'),
        description: t('删除成功'),
      }); //提示消息
    });
  }

  function handleSuccess() {
    reload({ searchInfo: { id: selectAreaId.value } });
  }
  const areaInfo = reactive({
    layer: 1,
    parentId: null,
  });
  function handleSelect(areaId = '', { selectedNodes }) {
    let { layer, parentId } = toRefs(areaInfo);
    layer.value = selectedNodes[0]?.layer + 1 || 1;
    parentId.value = selectedNodes[0]?.id;
    selectAreaId.value = areaId[0] || '';
    reload({ searchInfo: { id: areaId } });
  }
</script>
