<template>
  <ele-page>
    <el-card>
      <el-button
        class="ele-btn-icon"
        :icon="Refresh"
        @click="reload()"
        :loading="configLoading"
      >
        刷新
      </el-button>
      <el-button type="danger" class="ele-btn-icon" :icon="Refresh"  @click="sync()"  :loading="syncLoading">
        同步配置
      </el-button>
      <el-button type="success" class="ele-btn-icon"  @click="info()">
        配置列表
      </el-button>
    </el-card>

    <ele-card :body-style="{ paddingTop: '8px' }" v-loading="configLoading">
      <template #header>
        <ele-tabs
          type="tag"
          v-model="configGroup"
          :items="groupItems"
          @tabChange="reload()"
        />
      </template>
      <el-form
        ref="formRef"
        :model="form"
        label-position="top"
        @submit.prevent=""
      >
        <config-form-list
          ref="configFormListRef"
          :config-list="configList"
        />
        <el-form-item v-if="configList.length > 0">
          <div style="text-align: center;width: 100%;">
            <el-button type="primary" @click="saveForm">保存配置</el-button>
          </div>
        </el-form-item>
        <el-empty v-else description="没有定义配置列表" />
      </el-form>
    </ele-card>


    <ele-drawer
      size="100%"
      title="配置变更对比"
      :append-to-body="true"
      style="max-width: 100%"
      v-model="showInfo"
      :body-style="{ paddingBottom: '8px' }"
    >
      <div style="margin-bottom: 30px;">
        <el-descriptions
          class="margin-top"
          title="配置列表信息"
          :column="2"
          border
        >
          <el-descriptions-item label="缓存版本号">{{ infoData.cache_version }}</el-descriptions-item>
          <el-descriptions-item label="数据版本号">{{ infoData.table_version }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <monaco-editor
        v-model="infoData.table_php"
        language="php"
        v-model:original="infoData.cache_php"
        original-language="php"
        :diff="true"
        style="height: 460px"
      />
    </ele-drawer>
  </ele-page>
</template>

<script lang="ts" setup>
import {onMounted, ref } from 'vue';
import {Refresh} from '@element-plus/icons-vue';
import {infoConfigs, listConfigs, syncConfigs, updateConfigData} from '@/api/system/config';
import {getSysConfig, strToBind, strToOption} from '@/utils/sys-config';
import {useFormData} from '@/utils/use-form-data';
import type {Config} from '@/api/system/config/model';
import ConfigFormList from './components/config-form-list.vue';
import {EleMessage, toTree} from 'ele-admin-plus';
import MonacoEditor from "@/components/MonacoEditor/index.vue";

defineOptions({name: 'SystemConfigSet'});

/** 表单数据 */
const [form, resetFields, assignFields] = useFormData<Config>({});
const configList = ref([]);
const configLoading = ref(false);
const syncLoading = ref(false);

/** 搜索 */
const reload = () => {
  configLoading.value = true;
  listConfigs({group: configGroup.value, limit: 999}).then((data) => {
    const configs = data.filter((d) => d.type !== 'hidden');

    const lists = configs.map((d) => {
      // 解析vBind属性到item
      d.bind = strToBind(d.type, d.itemBind);
      d.option = strToOption(d.type, d.option);
      return d;
    });
    configList.value = toTree({
      data: lists,
      idField: 'id',
      parentIdField: 'pid'
    });

    configLoading.value = false;
  });
};

const sync = () => {
  syncLoading.value = true;
  syncConfigs().then(()=>{
    EleMessage.success("同步成功");
  }).finally(()=>{
    syncLoading.value = false;
  });
}

const showInfo = ref(false);
const infoData = ref<any>({
  cache_version: "",
  cache_php: "",
  table_php: "",
  table_version: "",
});
const info = ()=>{
  infoConfigs({}).then((data)=>{
    showInfo.value = true;
    infoData.value = {
      table_php: data.table_php,
      table_version: data.table_version,
      cache_version: data.cache_version,
      cache_php: data.cache_php,
    };
  })
}

const configFormListRef = ref(null);
const saveForm = () => {
  const allValues =  configFormListRef.value?.getFormData();
  console.log('所有组件数据:', allValues);
  updateConfigData(allValues).then(()=>{
    EleMessage.success("保存成功");
    reload();
  })
}

const groupItems = ref([]);
const configGroup = ref('');
onMounted(async () => {
  // 配置分组
  const group = [];
  const {valueData} = await getSysConfig('config_group');
  for (const name in valueData) {
    group.push({name: name, label: valueData[name]});
  }
  groupItems.value = group;
  if (group.length > 0) {
    configGroup.value = group[0].name;
  }
  reload();
});
</script>
