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

import {
  Button,
  Card,
  Input,
  InputNumber,
  InputPassword,
  message,
  Spin,
  Switch,
  Tag,
} from 'ant-design-vue';

import {
  getOaPlatformCredential,
  getOaPlatformList,
  updateOaPlatformCredential,
  updateOaPlatformEnabled,
} from '#/views/system/oa-platform/api';
import { getSystemConfigList, saveSystemConfig } from '#/views/system/system-config/api';

/**
 * 系统配置 - OA 通知 Tab
 * 总开关 + 平台子开关；work_wechat_app 可展开编辑平台级凭证
 */

const oaEnabled = ref(false);
const totalSaving = ref(false);
const platformsLoading = ref(false);
const platforms = ref<any[]>([]);
/** 当前展开编辑凭证的平台 id */
const editingCredId = ref<number | null>(null);
const credSaving = ref(false);
const credForm = ref({
  corp_id: '',
  agent_id: 0,
  app_secret: '',
  default_sender: '',
});

function isWorkWechatApp(code: string) {
  return code === 'work_wechat_app';
}

async function loadSystemConfig() {
  try {
    const list = await getSystemConfigList();
    const rows: any[] = Array.isArray(list) ? list : list?.data || [];
    const oaRow = rows.find((r) => r.config_key === 'oa_notify_enabled');
    oaEnabled.value = oaRow
      ? oaRow.config_value === '1' ||
        oaRow.config_value === 'true' ||
        oaRow.config_value === true
      : false;
  } catch (e) {
    console.error('加载系统配置失败', e);
  }
}

async function loadPlatforms() {
  platformsLoading.value = true;
  try {
    const list = await getOaPlatformList();
    platforms.value = Array.isArray(list) ? list : list?.data || [];
  } catch (e) {
    console.error('加载平台列表失败', e);
  } finally {
    platformsLoading.value = false;
  }
}

async function handleTotalSwitch(checked: boolean) {
  totalSaving.value = true;
  try {
    await saveSystemConfig([
      { config_key: 'oa_notify_enabled', config_value: checked ? '1' : '0' },
    ]);
    oaEnabled.value = checked;
    message.success(`OA 通知已${checked ? '启用' : '关闭'}`);
  } catch (e: any) {
    message.error(e.message || '保存失败');
    oaEnabled.value = !checked;
  } finally {
    totalSaving.value = false;
  }
}

async function handlePlatformSwitch(
  platform: any,
  checked: boolean,
  index: number,
) {
  const oldValue = platform.enabled;
  platforms.value[index].enabled = checked ? 1 : 0;
  try {
    await updateOaPlatformEnabled(platform.id, checked ? 1 : 0);
    message.success(`${platform.name} 已${checked ? '启用' : '关闭'}`);
  } catch (e: any) {
    platforms.value[index].enabled = oldValue;
    message.error(e.message || `${platform.name} 切换失败`);
  }
}

/** 展开/收起凭证编辑 */
async function toggleCredential(platform: any) {
  if (editingCredId.value === platform.id) {
    editingCredId.value = null;
    return;
  }
  editingCredId.value = platform.id;
  try {
    const data = await getOaPlatformCredential(platform.id);
    const row = data?.data ?? data ?? {};
    credForm.value = {
      corp_id: row.corp_id || '',
      agent_id: Number(row.agent_id || 0),
      app_secret: '',
      default_sender: row.default_sender || '',
    };
  } catch (e: any) {
    message.error(e.message || '加载凭证失败');
    editingCredId.value = null;
  }
}

async function saveCredential(platform: any) {
  credSaving.value = true;
  try {
    await updateOaPlatformCredential({
      id: platform.id,
      corp_id: credForm.value.corp_id,
      agent_id: Number(credForm.value.agent_id || 0),
      app_secret: credForm.value.app_secret || '',
      default_sender: credForm.value.default_sender || '',
    });
    message.success('平台凭证已保存');
    editingCredId.value = null;
    await loadPlatforms();
  } catch (e: any) {
    message.error(e.message || '保存失败');
  } finally {
    credSaving.value = false;
  }
}

onMounted(() => {
  loadSystemConfig();
  loadPlatforms();
});
</script>

<template>
  <div class="py-4">
    <Card class="mb-4">
      <div class="flex items-center justify-between">
        <div>
          <div class="mb-1 text-base font-medium">OA 通知总开关</div>
          <div class="text-sm text-gray-500">
            关闭后，所有场景的 OA 通知都将停止推送（包括所有平台）
          </div>
        </div>
        <Spin :spinning="totalSaving">
          <Switch
            :checked="oaEnabled"
            checked-children="开"
            un-checked-children="关"
            @change="handleTotalSwitch"
          />
        </Spin>
      </div>
    </Card>

    <Card :class="{ 'oa-platform-disabled': !oaEnabled }">
      <div class="mb-3 text-base font-medium">平台子开关</div>
      <div class="mb-2 text-sm text-gray-500">
        每个平台独立开关；企业微信（应用API）可配置平台级凭证供机器人继承
      </div>
      <Spin :spinning="platformsLoading">
        <div
          v-if="platforms.length === 0 && !platformsLoading"
          class="py-4 text-center text-gray-400"
        >
          暂无平台数据，请联系开发初始化
        </div>
        <div v-else class="space-y-3">
          <div
            v-for="(platform, index) in platforms"
            :key="platform.platform_code"
            class="rounded border border-gray-100 p-3"
          >
            <div class="flex items-center justify-between">
              <div class="flex items-center gap-3">
                <div>
                  <div class="flex items-center gap-2">
                    <span class="font-medium">{{ platform.name }}</span>
                    <Tag>{{ platform.platform_code }}</Tag>
                    <Tag
                      v-if="isWorkWechatApp(platform.platform_code)"
                      :color="platform.has_credential ? 'success' : 'default'"
                    >
                      {{ platform.has_credential ? '凭证已配' : '凭证未配' }}
                    </Tag>
                  </div>
                  <div class="text-xs text-gray-400">
                    排序：{{ platform.sort }}
                  </div>
                </div>
              </div>
              <div class="flex items-center gap-2">
                <Button
                  v-if="isWorkWechatApp(platform.platform_code)"
                  size="small"
                  type="link"
                  @click="toggleCredential(platform)"
                >
                  {{ editingCredId === platform.id ? '收起凭证' : '配置凭证' }}
                </Button>
                <Switch
                  :checked="platform.enabled === 1"
                  :disabled="!oaEnabled"
                  checked-children="启用"
                  un-checked-children="禁用"
                  @change="
                    (checked: boolean) =>
                      handlePlatformSwitch(platform, checked, index)
                  "
                />
              </div>
            </div>

            <div
              v-if="
                isWorkWechatApp(platform.platform_code) &&
                editingCredId === platform.id
              "
              class="mt-3 grid grid-cols-1 gap-3 border-t border-dashed border-gray-200 pt-3 md:grid-cols-2"
            >
              <div>
                <div class="mb-1 text-xs text-gray-500">企业 ID（corpid）</div>
                <Input
                  v-model:value="credForm.corp_id"
                  placeholder="请输入 corpid"
                />
              </div>
              <div>
                <div class="mb-1 text-xs text-gray-500">AgentId</div>
                <InputNumber
                  v-model:value="credForm.agent_id"
                  class="w-full"
                  :min="0"
                  placeholder="应用 agentid"
                />
              </div>
              <div>
                <div class="mb-1 text-xs text-gray-500">
                  应用 Secret（留空不改）
                </div>
                <InputPassword
                  v-model:value="credForm.app_secret"
                  placeholder="自建应用 Secret"
                  autocomplete="new-password"
                />
              </div>
              <div>
                <div class="mb-1 text-xs text-gray-500">
                  客户群群发默认 sender（userid）
                </div>
                <Input
                  v-model:value="credForm.default_sender"
                  placeholder="可选，群发任务执行人"
                />
              </div>
              <div class="md:col-span-2">
                <Button
                  type="primary"
                  size="small"
                  :loading="credSaving"
                  @click="saveCredential(platform)"
                >
                  保存凭证
                </Button>
              </div>
            </div>
          </div>
        </div>
      </Spin>
    </Card>
  </div>
</template>

<style scoped>
.oa-platform-disabled {
  opacity: 0.5;
  pointer-events: none;
}
</style>
