<template>
  <div class="app-container">
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="项目配置" name="projectConfig">
        <div class="monaco-block">
          <!-- ⭐ 高度控制容器 -->
          <div class="monaco-wrapper">
            <monaco-editor
              ref="wxEditor"
              v-model="projectYaml"
              language="yaml"
              theme="vs-dark"
              :options="monacoOptions"
            />
          </div>

          <div class="footer">
            <el-button type="primary" @click="submitProject">
              保存
            </el-button>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import {getConfigByKey, updateConfigByKey} from '@/api/system/config';
import {editTenantConfig, getTenantConfigByKey} from '@/api/tenant/tenant';
import yaml from "js-yaml";
import MonacoEditor from "vue-monaco";

export default {
  name: "ProjectConfigPage",

  components: {
    MonacoEditor
  },

  props: {
    tenantId: {
      type: [String, Number],
      default: null
    }
  },

  data() {
    return {
      activeName: "projectConfig",
      projectYaml: "",
      monacoOptions: {
        automaticLayout: true,
        minimap: { enabled: false },
        fontSize: 14,
        tabSize: 2,
        scrollBeyondLastLine: true,
        padding: {
          bottom: 40
        }
      },
      configId: null,
    };
  },

  created() {
    this.loadConfig(this.activeName);
  },

  mounted() {
  },

  methods: {
    loadConfig(key) {
      if (this.tenantId) {
        getTenantConfigByKey(key, this.tenantId).then(response => {
          if (response.data) {
            const data = response.data;
            this.configId = data.configId;
            const obj = JSON.parse(data.configValue);
            this.projectYaml = yaml.dump(obj);
          } else {
            // 租户配置为空，回退到系统配置接口
            this.configId = null;
            this.projectYaml = '';
            getConfigByKey(key).then(res => {
              if (res.data) {
                this.configId = res.data.configId;
                const obj = JSON.parse(res.data.configValue);
                this.projectYaml = yaml.dump(obj);
              }
            });
          }
        });
      } else {
        getConfigByKey(key).then(response => {
          if (!response.data) {
            this.configId = null;
            this.projectYaml = '';
            return;
          }
          const data = response.data;
          this.configId = data.configId;
          const obj = JSON.parse(data.configValue);
          this.projectYaml = yaml.dump(obj);
        });
      }
    },

    /** Tab 切换时强制 layout */
    handleClick(tab) {
      if (tab.name === "projectConfig") {
        this.$nextTick(() => {
          const editor = this.$refs.wxEditor?.editor;
          editor && editor.layout();
        });
      }
    },

    submitProject() {
      try {
        const json = yaml.load(this.projectYaml);
        if (!json || typeof json !== "object") {
          throw new Error("配置必须是对象");
        }
        const param = { configId: this.configId, configKey: this.activeName, configValue: JSON.stringify(json) }

        if (this.tenantId) {
          // 从租户管理页面进入，使用租户配置编辑接口
          param.id = this.tenantId;
          editTenantConfig(param).then(response => {
            if (response.code === 200) {
              this.msgSuccess('修改成功');
              this.$emit('success');
            }
          })
        } else {
          // 默认使用系统配置接口
          updateConfigByKey(param).then(response => {
            if (response.code === 200) {
              this.msgSuccess('修改成功')
            }
          })
        }
      } catch (e) {
        this.$message.error("YAML 格式错误：" + e.message);
      }
    }
  }
};
</script>

<style scoped>
.monaco-block {
  margin-top: 10px;
}

/* ⭐ 关键高度容器 */
.monaco-wrapper {
  height: 600px;
  width: 100%;
  border: 1px solid #ebeef5;
}

/* ⭐ 强制 vue-monaco 根节点撑满高度 */
.monaco-wrapper > div {
  height: 100% !important;
}

/* 底部按钮 */
.footer {
  margin-top: 16px;
  text-align: right;
}
</style>
