<template>
  <div class="gl-page-content">
    <div class="gl-page-content-title">
      <div class="return-button">
        <el-icon class="ft28" @click="backUpFn">
          <ArrowLeft />
        </el-icon>
      </div>
      <div class="app-img mr12">
        <img v-if="currentAppInfo?.appImage" width="40" :src="getImgPathFn(currentAppInfo?.appImage)" alt="">
        <div v-else class="app-bg-content">
          <appNameBg :app-name="currentAppInfo.appName" :size="20"></appNameBg>

        </div>
      </div>
      <div class="app-name mr12">
        {{ currentAppInfo.appName }}
      </div>
      <div class="app-status mr12">
        <div :class="currentAppInfo.appStatus === '1' ? 'point success mr5' : 'point error mr5'"></div>
        <span>{{ currentAppInfo.appStatus === '1' ? '启用' : '禁用' }}</span>
      </div>
      <div class="app-type mr12">
        <el-tag v-if="currentAppInfo.appType === '3'" type="primary">HPC</el-tag>
        <el-tag v-if="currentAppInfo.appType === '2'" type="success">云应用</el-tag>
        <el-tag v-if="currentAppInfo.appType === '1'" type="warning">本地应用</el-tag>
      </div>
    </div>

    <div class="page-content">
      <div class="filter-box">
        <el-form :model="filterFormData">
          <el-form-item label="配置名称：">
            <el-select v-model="filterFormData.configName" class="select-style" @change="configChangeFn">
              <el-option
                v-for="item in configList"
                :value="item.id"
                :key="item.id"
                :label="item.configName"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="addConfigFn">新增配置</el-button>
            <el-button type="danger" @click="delConfigFn">删除配置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- APP_CONFIG_TABLE -->
      <div class="page-table-content">
        <BaseTable tableName="APP_CONFIG_TABLE" ref="baseTableRef" hidePagination>
          <template #leftOptions>
            <el-button type="primary" @click="openAddParamFn">新增参数</el-button>
          </template>

          <template #operate="{ row }">
            <el-button type="danger" link @click="delConfigParamFn(row)">删除</el-button>
          </template>
        </BaseTable>
      </div>

    </div>

    <addConfig
      v-if="appConfigVisible"
      :config-info="configData"
      @cancel="appConfigVisible = false"
      @submit="addConfigInfo"
    >
    </addConfig>

    <addConfigParam
      v-if="appConfigParamVisible"
      :current-config="currentConfigInfo"
      @cancel="appConfigParamVisible = false"
      @submit="addConfigParamFn"
      :table-name="'APP_CONFIG_TABLE'"
    >
    </addConfigParam>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, reactive } from 'vue';
import BaseTable from '@/components/common/table/baseTable.vue';
import appNameBg from '@/views/task/appCenter/components/appNameBg.vue';
import addConfig from './addConfig.vue';
import { addApplicationConfigApi, deleteApplicationConfigAPi, queryApplicationConfigApi, updateApplicationConfigAPi } from '@/api/system/application';
import addConfigParam from './addConfigParam.vue';
import { ElMessage } from 'element-plus';

const props = defineProps(['appInfo']);
const emits = defineEmits(['backUp']);
const env = import.meta.env;
const baseTableRef = ref();
const currentAppInfo = ref<any>({});

const appConfigVisible = ref(false);
const appConfigParamVisible = ref(false);

const getImgPathFn = (fileId: any) => {
  const url = `${env.VITE_API_IMAGE_PREVIEW_URL}/data/previewImage?fileId=${fileId}`;
  return url;
};

const currentConfigInfo = ref<any>();

const filterFormData = reactive<any>({
  configName: '',

});

const configChangeFn = () => {
  currentConfigInfo.value = configList.value.find((item: any) => {
    return item.id === filterFormData.configName;
  });

  getConfigTableDataFn(currentConfigInfo.value.configValue);
};

const configList = ref<any>([]);

const configData = ref<any>({});
const addConfigFn = () => {
  configData.value = {};

  appConfigVisible.value = true;

};

const addConfigInfo = async (data: any) => {
  const res: any = await addApplicationConfigApi({
    appName: currentAppInfo.value.appName,
    appId: currentAppInfo.value.uuid,
    configName: data.configName,
    configValue: '',
    configType: data.configType,
    appVendor: currentAppInfo.value.appVendor,
    machineCode: currentAppInfo.value.machineCode,
    comment: data.comment,
  });

  if (res && res.code === 200) {
    getAppConfigListFn();
  }
  console.log(data, 'data');
  appConfigVisible.value = false;

};

const getAppConfigListFn = async () => {

  const res: any = await queryApplicationConfigApi({
    appId: currentAppInfo.value.uuid,
  });
  if (res && res.code === 200) {
    configList.value = res.data;

    if (configList.value.length) {

      if (!filterFormData.configName) {
        filterFormData.configName = configList.value[0].id;
      }
      configChangeFn();
    } else {
      tableData.value = [];
    }

  }

};

const tableData = ref<any>([]);
const getConfigTableDataFn = (val: any) => {
  if (val) {
    tableData.value = JSON.parse(val);
  } else {
    tableData.value = [];
  }

  baseTableRef.value.setDataFun(tableData.value);

};

const backUpFn = () => {
  emits('backUp');
};

const openAddParamFn = () => {
  appConfigParamVisible.value = true;
};

const addConfigParamFn = async (data: any) => {
  const addData: any = { ...data, id: new Date().getTime() };

  const result = tableData.value.find((item: any) => {
    return item.name === data.name;
  });

  if (result) {
    ElMessage.warning('已存在该参数，无法重复添加！');
    return;
  }

  if (!tableData.value) {
    tableData.value = [];
  }

  tableData.value.push(addData);
  baseTableRef.value.setDataFun(tableData.value);

  const res: any = await updateApplicationConfigAPi({
    ...currentConfigInfo.value,
    configValue: JSON.stringify(tableData.value),
  });

  if (res && res.code === 200) {
    ElMessage.success('添加成功');
    await getAppConfigListFn();
  }

  appConfigParamVisible.value = false;
};

const delConfigParamFn = async (row: any) => {

  tableData.value = tableData.value.filter((item: any) => {
    return item.id != row.id;
  });
  baseTableRef.value.setDataFun(tableData.value);

  console.log(tableData.value, 'tableData.value');

  const res: any = await updateApplicationConfigAPi({
    ...currentConfigInfo.value,
    configValue: JSON.stringify(tableData.value),
  });

  if (res && res.code === 200) {
    ElMessage.success('更新成功');
    await getAppConfigListFn();
  }

};

const delConfigFn = async () => {
  if (filterFormData.configName) {

    const res: any = await deleteApplicationConfigAPi({
      configId: filterFormData.configName,
    });

    if (res && res.code === 200) {
      filterFormData.configName = '';
      ElMessage.success('删除成功');
      getAppConfigListFn();

    }

  } else {
    ElMessage.error('请选择应用配置后删除！');
  }
};

watch(() => props.appInfo, async (newVal) => {
  currentAppInfo.value = newVal;
  await getAppConfigListFn();
}, {
  immediate: true,
  deep: true,
});
</script>

<style lang="scss" scoped>
.gl-page-content {
  width: 100%;
  height: 100%;

  .gl-page-content-title {
    width: 100%;
    height: 50px;
    display: flex;
    align-items: center;

    .ft28 {
      font-size: 28px;
      margin-right: 12px;
      cursor: pointer;
    }

    .mr12 {
      margin-right: 12px;

    }

    .mr5 {
      margin-right: 5px;

    }

    .app-name {
      font-size: 30px;
      min-width: 100px;
    }

    .app-status {
      height: 100%;
      display: flex;
      align-items: center;
    }

    .app-bg-content {
      width: 40px;
      height: 40px;
      border-radius: 5px;
      overflow: hidden;
    }

    .point {
      width: 8px;
      height: 8px;
      border-radius: 50%;
    }

    .success {
      background-color: #67C23A;
    }

    .error {
      background-color: #F56C6C;
    }
  }

  .page-content {
    width: 100%;
    height: calc(100% - 60px);
    margin-top: 10px;

    .filter-box {
      width: 100%;
      height: 40px;

      .el-form {
        display: flex;

        .select-style {
          width: 200px;
          margin-right: 12px;
        }
      }
    }

    .page-table-content {
      width: 100%;
      height: calc(100% - 50px);
      margin-top: 10px;
    }
  }
}
</style>
