<script lang="ts" setup>
import { onMounted, watch } from 'vue';

import { Page, useVbenModal } from '@vben/common-ui';

import { Button, Empty, message } from 'ant-design-vue';
import { PlusOutlined } from '@ant-design/icons-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import type { ContextMenuItem } from '#/components/context-menu';
import { showContextMenu } from '#/components/context-menu';
import ConfigSectionHeader from '#/views/system/shared/config-section-header.vue';
import ConfigTreeSidebar from '#/views/system/shared/config-tree-sidebar.vue';
import type { TreeSidebarRow } from '#/views/system/shared/types';
import InlineFieldEditor from '#/views/system/process/components/inline-field-editor.vue';

import { deleteRegion, updateRegion } from './api';
import FormModalDemo from './components/modal.vue';
import MovePidModal from './components/move-pid-modal.vue';
import RegionInfoBar from './components/region-info-bar.vue';
import { useRegionTree } from './composables/useRegionTree';
import type { RegionRow } from './constants';
import { childGridOptions } from './config/child-table';

const {
  currentChildren,
  filteredLevel1,
  keyword,
  level1List,
  loadData,
  loading,
  patchRegion,
  selectLevel1,
  selectedLevel1,
  selectedLevel1Id,
} = useRegionTree();

const [FormModal, formModalApi] = useVbenModal({
  connectedComponent: FormModalDemo,
});

const [MoveModal, moveModalApi] = useVbenModal({
  connectedComponent: MovePidModal,
});

const [ChildGrid, childGridApi] = useVbenVxeGrid({
  gridOptions: {
    ...childGridOptions,
    data: [],
  },
});

function syncChildGrid() {
  childGridApi.setGridOptions({ data: currentChildren.value });
}

onMounted(async () => {
  await loadData();
  syncChildGrid();
});

watch(currentChildren, syncChildGrid, { deep: true });
watch(selectedLevel1Id, syncChildGrid);

function refresh() {
  return loadData().then(syncChildGrid);
}

function formatFee(value: unknown) {
  if (value === null || value === undefined || value === '') {
    return '点击设置';
  }
  const num = Number(value);
  return Number.isFinite(num) ? `¥${num.toFixed(2)}` : String(value);
}

function openCreateModal(options: {
  formLevel: number;
  isUpdate?: boolean;
  parentRow?: RegionRow;
  values?: Record<string, any>;
}) {
  const { formLevel, isUpdate = false, parentRow, values = {} } = options;
  let formValues: Record<string, any> = { ...values, formLevel };

  if (!isUpdate) {
    if (formLevel === 1) {
      formValues = { pid: 0, formLevel: 1, express_fee: 0 };
    } else if (formLevel === 2 && parentRow) {
      formValues = {
        pid: parentRow.id,
        formLevel: 2,
        express_fee: 0,
      };
    }
  }

  formModalApi.setData({
    values: formValues,
    update: isUpdate,
    formLevel,
    onSuccess: refresh,
  });
  formModalApi.open();
}

function openMoveModal(row: RegionRow) {
  moveModalApi.setData({
    target: row,
    level1List: level1List.value,
    onSuccess: refresh,
  });
  moveModalApi.open();
}

function buildLevel1Menus(row: RegionRow): ContextMenuItem[] {
  return [
    {
      key: 'add-child',
      label: '新增子地区',
      handler: () => openCreateModal({ formLevel: 2, parentRow: row }),
    },
  ];
}

function buildChildMenus(row: RegionRow): ContextMenuItem[] {
  return [
    {
      key: 'move-pid',
      label: '移动父级',
      handler: () => openMoveModal(row),
    },
    {
      key: 'delete',
      label: '删除',
      handler: async () => {
        await deleteRegion({ ids: [row.id] });
        message.success('删除成功');
        await refresh();
      },
    },
  ];
}

function onLevel1ContextMenu(e: MouseEvent, row: TreeSidebarRow) {
  showContextMenu(e, buildLevel1Menus(row as RegionRow), row);
}

function onChildContextMenu(e: MouseEvent, row: RegionRow) {
  showContextMenu(e, buildChildMenus(row), row);
}

async function saveLevel1Name(row: TreeSidebarRow, name: string) {
  const region = row as RegionRow;
  await updateRegion({ id: region.id, name });
  patchRegion(region.id, { name });
  message.success('保存成功');
}

async function saveChildField(
  row: RegionRow,
  field: 'express_fee' | 'name',
  value: number | string,
) {
  const payload: Record<string, unknown> = { id: row.id };
  if (field === 'name') {
    payload.name = value;
  } else {
    payload.express_fee = value;
  }
  await updateRegion(payload);
  patchRegion(
    row.id,
    field === 'name' ? { name: String(value) } : { express_fee: value },
  );
  message.success('保存成功');
}

function onSelectLevel1(id: number) {
  selectLevel1(id);
  syncChildGrid();
}

function openCreateChild() {
  if (!selectedLevel1.value) {
    return;
  }
  openCreateModal({ formLevel: 2, parentRow: selectedLevel1.value });
}
</script>

<template>
  <Page
    auto-content-height
    description="右键地区或子地区行可新增/移动；点击虚线下划线字段可编辑"
    title="快递费管理"
  >
    <FormModal />
    <MoveModal />

    <div class="flex h-full min-h-0 gap-4">
      <ConfigTreeSidebar
        add-label="新增地区"
        empty-text="暂无地区"
        :filtered-level1="filteredLevel1"
        :keyword="keyword"
        :loading="loading"
        search-placeholder="搜索地区名称"
        :selected-level1-id="selectedLevel1Id"
        title="地区"
        :total-count="level1List.length"
        @add-level1="openCreateModal({ formLevel: 1 })"
        @contextmenu="onLevel1ContextMenu"
        @save-name="saveLevel1Name"
        @select="onSelectLevel1"
        @update:keyword="(val) => (keyword = val)"
      />

      <main
        class="min-w-0 flex-1 rounded-lg border border-border bg-card px-4 py-3 dark:border-gray-700"
      >
        <template v-if="selectedLevel1">
          <div class="space-y-4">
            <div
              class="flex flex-wrap items-center justify-between gap-3 border-b border-border pb-3"
            >
              <span class="text-sm font-medium text-foreground">{{
                selectedLevel1.name
              }}</span>
              <Button size="small" @click="openCreateChild">
                <PlusOutlined />
                新增子地区
              </Button>
            </div>

            <RegionInfoBar
              :region="selectedLevel1"
              @updated="
                (patch) => patchRegion(selectedLevel1!.id, patch)
              "
            />

            <section
              class="rounded-lg border border-border dark:border-gray-700"
            >
              <ConfigSectionHeader
                class="mb-3 px-4 pt-3"
                :subtitle="`共 ${currentChildren.length} 条`"
                title="子地区列表"
              >
                <template #actions>
                  <Button size="small" type="primary" @click="openCreateChild">
                    <PlusOutlined />
                    新增子地区
                  </Button>
                </template>
              </ConfigSectionHeader>

              <div
                v-if="currentChildren.length"
                class="overflow-hidden rounded-b-lg border-t border-border dark:border-gray-700"
              >
                <ChildGrid @contextmenu.prevent>
                  <template #name="{ row }">
                    <span @contextmenu="onChildContextMenu($event, row)">
                      <InlineFieldEditor
                        :value="row.name"
                        @save="(val) => saveChildField(row, 'name', val)"
                      />
                    </span>
                  </template>
                  <template #express_fee="{ row }">
                    <span @contextmenu="onChildContextMenu($event, row)">
                      <InlineFieldEditor
                        type="number"
                        :value="row.express_fee"
                        :display-formatter="formatFee"
                        @save="(val) => saveChildField(row, 'express_fee', val)"
                      />
                    </span>
                  </template>
                </ChildGrid>
              </div>
              <div
                v-else
                class="flex flex-col items-center justify-center px-4 py-8"
              >
                <Empty description="暂无子地区" />
                <Button class="mt-4" type="primary" @click="openCreateChild">
                  <PlusOutlined />
                  新增子地区
                </Button>
              </div>
            </section>
          </div>
        </template>
        <Empty v-else description="请选择左侧地区" />
      </main>
    </div>
  </Page>
</template>
