<script lang="ts" setup>
import type { SpreadsheetConfigJson } from '../config/spreadsheetDefaults';

import { computed, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';
import { useUserStore } from '@vben/stores';

import {
  Alert,
  Button,
  Checkbox,
  Input,
  List,
  message,
  Popconfirm,
  Space,
  Tabs,
  Textarea,
} from 'ant-design-vue';

import {
  createSpreadsheetTableConfig,
  deleteSpreadsheetTableConfig,
  listSpreadsheetTableConfig,
  type SpreadsheetTableConfigItem,
  updateSpreadsheetTableConfig,
} from '#/api/spreadsheet-table-config';

import {
  getWarehouseSpreadsheetDefaults,
  mergeSpreadsheetConfig,
  WAREHOUSE_SPREADSHEET_TABLE_NAME,
  warehouseSpreadsheetSheetKey,
} from '../config/spreadsheetDefaults';
import { canManageSpreadsheetConfig } from '../utils/spreadsheetAdminRole';

import SpreadsheetConfigFormEditor from './SpreadsheetConfigFormEditor.vue';

const props = defineProps<{
  productType: number;
}>();

const emit = defineEmits<{
  saved: [];
}>();

const userStore = useUserStore();

const items = ref<SpreadsheetTableConfigItem[]>([]);
const loading = ref(false);
const selectedId = ref<number | null>(null);
const formName = ref('默认');
const formIsDefault = ref(false);
const formJson = ref('');
const formConfig = ref<SpreadsheetConfigJson>(
  getWarehouseSpreadsheetDefaults(props.productType),
);
const jsonError = ref('');
const activeTab = ref<'form' | 'json'>('form');

let listLoadToken = 0;

const sheetKey = computed(() => warehouseSpreadsheetSheetKey(props.productType));

const isSuperAdmin = computed(() =>
  canManageSpreadsheetConfig(userStore.userInfo),
);

const selectedItem = computed(() =>
  items.value.find((i) => i.id === selectedId.value),
);

const isSystemConfig = computed(() => selectedItem.value?.admin_id === 0);

const isReadOnly = computed(() => isSystemConfig.value && !isSuperAdmin.value);

function formatJson(config: SpreadsheetConfigJson) {
  return JSON.stringify(config, null, 2);
}

function syncJsonFromConfig(config: SpreadsheetConfigJson) {
  formConfig.value = config;
  formJson.value = formatJson(config);
  jsonError.value = '';
}

function parseJson(): SpreadsheetConfigJson | null {
  jsonError.value = '';
  try {
    const parsed = JSON.parse(formJson.value) as SpreadsheetConfigJson;
    if (!Array.isArray(parsed.headers) || !Array.isArray(parsed.columns)) {
      jsonError.value = 'config 需包含 headers 与 columns 数组';
      return null;
    }
    return parsed;
  } catch {
    jsonError.value = 'JSON 格式无效';
    return null;
  }
}

function getConfigForSave(): SpreadsheetConfigJson | null {
  if (activeTab.value === 'form') {
    return formConfig.value;
  }
  const parsed = parseJson();
  if (parsed) {
    formConfig.value = parsed;
  }
  return parsed;
}

function onTabChange(key: string | number) {
  if (key === 'json' && activeTab.value === 'form') {
    formJson.value = formatJson(formConfig.value);
    jsonError.value = '';
  } else if (key === 'form' && activeTab.value === 'json') {
    const parsed = parseJson();
    if (!parsed) {
      message.warning('JSON 格式无效，请修正后再切换表单');
      return;
    }
    formConfig.value = parsed;
  }
  activeTab.value = key as 'form' | 'json';
}

function onFormConfigUpdate(config: SpreadsheetConfigJson) {
  formConfig.value = config;
  if (activeTab.value === 'form') {
    formJson.value = formatJson(config);
  }
}

async function loadList() {
  const token = ++listLoadToken;
  loading.value = true;
  try {
    const list = await listSpreadsheetTableConfig({
      table_name: WAREHOUSE_SPREADSHEET_TABLE_NAME,
      sheet_key: sheetKey.value,
    });
    if (token !== listLoadToken) return;
    items.value = list;
    if (items.value.length === 0) {
      selectedId.value = null;
      resetFormFromDefaults();
      return;
    }
    const current =
      items.value.find((i) => i.id === selectedId.value) ??
      items.value.find((i) => i.is_default === 1) ??
      items.value[0];
    if (current) selectItem(current);
  } catch {
    if (token !== listLoadToken) return;
    items.value = [];
    resetFormFromDefaults();
  } finally {
    if (token === listLoadToken) {
      loading.value = false;
    }
  }
}

function resetFormFromDefaults() {
  formName.value = '默认';
  formIsDefault.value = true;
  syncJsonFromConfig(getWarehouseSpreadsheetDefaults(props.productType));
}

function selectItem(item: SpreadsheetTableConfigItem) {
  selectedId.value = item.id;
  formName.value = item.name;
  formIsDefault.value = item.is_default === 1;
  syncJsonFromConfig(item.config);
  activeTab.value = 'form';
}

function handleNew() {
  selectedId.value = null;
  resetFormFromDefaults();
  formName.value = `方案${items.value.length + 1}`;
  formIsDefault.value = false;
  activeTab.value = 'form';
}

function handleFormat() {
  const parsed = parseJson();
  if (parsed) {
    formJson.value = formatJson(parsed);
    formConfig.value = parsed;
  }
}

async function handleSave(): Promise<boolean> {
  if (isReadOnly.value) {
    message.warning('系统默认配置不可编辑');
    return false;
  }

  const config = getConfigForSave();
  if (!config) return false;

  const payload = {
    table_name: WAREHOUSE_SPREADSHEET_TABLE_NAME,
    sheet_key: sheetKey.value,
    name: formName.value.trim() || '默认',
    is_default: formIsDefault.value,
    config: mergeSpreadsheetConfig(
      config,
      getWarehouseSpreadsheetDefaults(props.productType),
    ),
  };

  try {
    if (selectedId.value) {
      await updateSpreadsheetTableConfig({
        id: selectedId.value,
        name: payload.name,
        is_default: payload.is_default,
        config: payload.config,
      });
      message.success('更新成功');
    } else {
      await createSpreadsheetTableConfig(payload);
      message.success('创建成功');
    }
    await loadList();
    emit('saved');
    return true;
  } catch (err: any) {
    message.error(err?.message ?? '保存失败');
    return false;
  }
}

async function handleDelete(id: number) {
  try {
    await deleteSpreadsheetTableConfig(id);
    message.success('删除成功');
    if (selectedId.value === id) selectedId.value = null;
    await loadList();
    emit('saved');
  } catch (err: any) {
    message.error(err?.message ?? '删除失败');
  }
}

const [Modal, modalApi] = useVbenModal({
  fullscreen: true,
  fullscreenButton: true,
  confirmText: '确定',
  cancelText: '取消',
  showConfirmButton: true,
  onConfirm: async () => {
    return handleSave();
  },
  onOpenChange(isOpen) {
    if (isOpen) {
      modalApi.setState({ fullscreen: true });
      void loadList();
    } else {
      listLoadToken += 1;
      loading.value = false;
    }
  },
});

defineExpose({
  open: () => modalApi.open(),
});
</script>

<template>
  <Modal title="Excel 表格配置">
    <div class="config-modal-body">
      <div class="config-list-pane">
        <Space class="config-list-actions">
          <Button size="small" type="primary" @click="handleNew">新建</Button>
          <Button size="small" :loading="loading" @click="loadList">刷新</Button>
        </Space>
        <List
          :data-source="items"
          :loading="loading"
          size="small"
          bordered
        >
          <template #renderItem="{ item }">
            <List.Item
              class="config-list-item"
              :class="{ active: item.id === selectedId }"
              @click="selectItem(item)"
            >
              <div class="config-list-item-main">
                <span>{{ item.name }}</span>
                <span v-if="item.admin_id === 0" class="system-tag">系统</span>
                <span v-if="item.is_default === 1" class="default-tag">默认</span>
              </div>
              <Popconfirm
                v-if="item.admin_id !== 0"
                title="确定删除该配置？"
                @confirm="handleDelete(item.id)"
              >
                <Button danger size="small" type="link" @click.stop>删除</Button>
              </Popconfirm>
            </List.Item>
          </template>
        </List>
      </div>

      <div class="config-editor-pane">
        <Space direction="vertical" class="config-editor-form" :size="12">
          <Input
            v-model:value="formName"
            :disabled="isReadOnly"
            addon-before="名称"
          />
          <Checkbox v-model:checked="formIsDefault" :disabled="isReadOnly">
            设为默认
          </Checkbox>

          <Alert
            v-if="isReadOnly"
            message="系统默认配置仅管理员（role 1/2）可编辑"
            show-icon
            type="info"
          />
          <Alert
            v-else-if="isSystemConfig && isSuperAdmin"
            message="正在编辑系统默认配置，保存后对所有用户生效"
            show-icon
            type="warning"
          />

          <Tabs :active-key="activeTab" @change="onTabChange">
            <Tabs.TabPane key="form" tab="表单编辑">
              <SpreadsheetConfigFormEditor
                :config="formConfig"
                :disabled="isReadOnly"
                @update:config="onFormConfigUpdate"
              />
            </Tabs.TabPane>
            <Tabs.TabPane key="json" tab="JSON 高级">
              <div class="json-toolbar">
                <span>config JSON</span>
                <Button :disabled="isReadOnly" size="small" @click="handleFormat">
                  格式化
                </Button>
              </div>
              <Textarea
                v-model:value="formJson"
                :auto-size="{ minRows: 14, maxRows: 22 }"
                :disabled="isReadOnly"
                class="json-textarea"
              />
            </Tabs.TabPane>
          </Tabs>

          <div v-if="jsonError" class="json-error">{{ jsonError }}</div>
        </Space>
      </div>
    </div>
  </Modal>
</template>

<style scoped lang="scss">
.config-modal-body {
  display: flex;
  gap: 16px;
  min-height: calc(100vh - 180px);
}

.config-list-pane {
  width: 220px;
  flex-shrink: 0;
}

.config-list-actions {
  margin-bottom: 8px;
}

.config-list-item {
  cursor: pointer;

  &.active {
    background: rgba(22, 93, 255, 0.08);
  }
}

.config-list-item-main {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
  flex-wrap: wrap;
}

.default-tag {
  font-size: 12px;
  color: #165dff;
}

.system-tag {
  font-size: 12px;
  color: #722ed1;
}

.config-editor-pane {
  flex: 1;
  min-width: 0;
}

.config-editor-form {
  width: 100%;
}

.json-toolbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 8px;
}

.json-textarea {
  font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
  font-size: 12px;
}

.json-error {
  color: #ff4d4f;
  font-size: 12px;
}
</style>
