<template>
  <div class="base-collapse">
    <div class="header"> 上辅机中间库 </div>
    <a-collapse expand-icon-position="right" :bordered="false">
      <a-collapse-panel key="1">
        <template #header>
          <div style="font-size: 16px"> 1.配置说明</div>
        </template>
        <div class="base-desc">
          在此配置 SQL Server 中间库（MES_ShareDB）连接信息。<strong>保存后立即生效，无需重启后端</strong>，也无需修改 application.yml。
          读取开关控制 MCS→MES 方向数据查询；写入开关控制 MES→MCS 方向数据写入。
        </div>
      </a-collapse-panel>
    </a-collapse>
    <div class="sync-padding">
      <a-collapse expand-icon-position="right" :bordered="false">
        <a-collapse-panel key="2">
          <template #header>
            <div style="width: 100%; justify-content: space-between; display: flex">
              <div style="font-size: 16px"> 2.连接信息及开关</div>
            </div>
          </template>
          <a-alert v-if="connStatus" type="info" show-icon style="margin-bottom: 12px" message="当前运行状态" :description="connStatus" />
          <div class="flex-flow">
            <div class="base-title">服务器</div>
            <div class="base-message">
              <a-input :value="displayHost" readonly />
            </div>
          </div>
          <div class="flex-flow">
            <div class="base-title">数据库</div>
            <div class="base-message">
              <a-input :value="configData.dbName || '-'" readonly />
            </div>
          </div>
          <div class="flex-flow">
            <div class="base-title">用户名</div>
            <div class="base-message">
              <a-input :value="configData.dbUsername || '-'" readonly />
            </div>
          </div>
          <div class="flex-flow">
            <div class="base-title">读取开关</div>
            <div class="base-message" style="display: flex; align-items: center; height: 50px">
              <a-tag :color="runtimeStatus.readEnabled ? 'green' : 'default'">{{ runtimeStatus.readEnabled ? '已开启' : '已关闭' }}</a-tag>
            </div>
          </div>
          <div class="flex-flow">
            <div class="base-title">写入开关</div>
            <div class="base-message" style="display: flex; align-items: center; height: 50px">
              <a-tag :color="runtimeStatus.writeEnabled ? 'green' : 'default'">{{ runtimeStatus.writeEnabled ? '已开启' : '已关闭' }}</a-tag>
            </div>
          </div>
          <div class="flex-flow">
            <div class="base-title">连接状态</div>
            <div class="base-message" style="display: flex; align-items: center; height: 50px">
              <a-tag :color="runtimeStatus.dbConfigActive ? 'green' : 'orange'">{{ runtimeStatus.dbConfigActive ? '已启用数据库配置' : '使用 yml 默认配置' }}</a-tag>
            </div>
          </div>
          <div style="margin-top: 20px; width: 100%; text-align: right">
            <a-button type="primary" @click="editClick">编辑配置</a-button>
            <a-button @click="testClick" style="margin-left: 10px">连接测试</a-button>
            <a-button v-if="configData.id" @click="deleteClick" danger style="margin-left: 10px">删除配置</a-button>
          </div>
        </a-collapse-panel>
      </a-collapse>
    </div>
  </div>

  <McsDbConfigModal @register="registerModal" @success="reload" />
</template>

<script lang="ts">
  import { computed, defineComponent, onMounted, ref } from 'vue';
  import { Modal } from 'ant-design-vue';
  import { useModal } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { getTenantId } from '/@/utils/auth';
  import McsDbConfigModal from './McsDbConfigModal.vue';
  import { deleteMcsDbConfig, getMcsDbConfig, getMcsDbStatus, testMcsDbConnect } from './McsDbConfig.api';

  export default defineComponent({
    name: 'ThirdAppMcsDbConfigForm',
    components: { McsDbConfigModal },
    setup() {
      const { createMessage } = useMessage();
      const configData = ref<any>({});
      const runtimeStatus = ref<any>({ dbConfigActive: false, readEnabled: true, writeEnabled: true });
      const [registerModal, { openModal }] = useModal();

      const displayHost = computed(() => {
        if (!configData.value.serverHost) return '-';
        const port = configData.value.serverPort || 1433;
        return `${configData.value.serverHost}:${port}`;
      });

      const connStatus = computed(() => {
        const s = runtimeStatus.value;
        if (!configData.value.id) {
          return '尚未保存数据库配置，当前使用 application.yml 中的 sqlserver_mcs 默认连接。';
        }
        return `读取：${s.readEnabled ? '开' : '关'} | 写入：${s.writeEnabled ? '开' : '关'} | 连接：${s.dbConfigActive ? '已启用数据库配置' : '使用 yml 默认配置'}`;
      });

      async function reload() {
        const tenantId = getTenantId();
        configData.value = (await getMcsDbConfig({ tenantId })) || {};
        runtimeStatus.value = (await getMcsDbStatus()) || {};
      }

      function editClick() {
        openModal(true, {});
      }

      async function testClick() {
        const tenantId = getTenantId();
        const res = await testMcsDbConnect({ tenantId });
        if (res.success) {
          createMessage.success(res.message || '连接成功');
        } else {
          createMessage.warning(res.message || '连接失败');
        }
      }

      function deleteClick() {
        Modal.confirm({
          title: '删除配置',
          content: '删除后将断开数据库中的中间库配置，系统回退使用 application.yml 默认连接。确认删除？',
          okText: '确认',
          cancelText: '取消',
          onOk: async () => {
            await deleteMcsDbConfig({ id: configData.value.id });
            createMessage.success('已删除');
            await reload();
          },
        });
      }

      onMounted(reload);

      return {
        configData,
        runtimeStatus,
        displayHost,
        connStatus,
        registerModal,
        editClick,
        testClick,
        deleteClick,
        reload,
      };
    },
  });
</script>

<style lang="less" scoped>
  .header {
    align-items: center;
    box-sizing: border-box;
    display: flex;
    height: 50px;
    justify-content: space-between;
    font-weight: 700;
    font-size: 18px;
    color: @text-color;
  }

  .flex-flow {
    display: flex;
    min-height: 0;
  }

  .sync-padding {
    padding: 12px 0 16px;
    color: @text-color;
  }

  .base-collapse {
    margin-top: 20px;
    padding: 0 24px;
    font-size: 20px;

    .base-desc {
      font-size: 14px;
    }

    .base-title {
      width: 100px;
      text-align: left;
      height: 50px;
      line-height: 50px;
    }

    .base-message {
      width: 100%;
      height: 50px;
      line-height: 50px;
    }

    :deep(.ant-collapse-header) {
      padding: 12px 0 16px;
    }

    :deep(.ant-collapse-content-box) {
      padding-left: 0;
    }
  }
</style>
